package com.railwayservice.common.web;

import com.railwayservice.application.exception.AppException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义全局异常处理类
 */
public class GlobalExceptionResolver implements HandlerExceptionResolver {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    private static final String MESSAGE = "操作失败，请稍候再试。";

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        LOGGER.error("服务异常：" + ex.getMessage(), ex);
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        Map<String, Object> result = new HashMap<>(4);
        result.put("success", false);
        if (ex instanceof AppException) {
            AppException ae = (AppException) ex;
            result.put("code", ae.getCode());
            result.put("message", ae.getMessage());
            result.put("data", ae.getData());
        } else {
            result.put("code", 2);
            result.put("message", MESSAGE);
            result.put("data", ex.getMessage());
        }
        view.setAttributesMap(result);
        return new ModelAndView(view);
    }

}